import axios from "axios"
import { Message } from "element-ui"
import store from "@/store"
import Vue from "vue"
import localCache from "@/utils/cache"
import { TOKEN } from "@/utils/settings"

import router from "@/router"
/**
 *
 * @param {Object} apiConfig 网络请求config
 * @param {Boolean} notToken 为true时请求不带token
 * @returns AxiosInstance
 */
export default function (apiConfig, notToken = false) {
  const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_URL,
    timeout: process.env.VUE_APP_TIME_OUT
  })

  // 请求拦截器
  service.interceptors.request.use(
    (config) => {
      if (store.getters.token && !notToken) {
        config.headers["Authorization"] = "Bearer " + store.getters.token
      }
      return config
    },
    (error) => {
      // do something with request error
      console.log(error) // for debug
      return Promise.reject(error)
    }
  )

  // 响应拦截器
  service.interceptors.response.use(
    (response) => {
      const res = response.data
      if (Object.prototype.toString.call(res) === "[object Blob]") return res
      if (res.code !== Vue.prototype.$code) {
        Message({
          message: res.msg || "Error",
          type: "error",
          duration: 5 * 1000
        })
        return Promise.reject(res)
      } else {
        return res
      }
    },
    (error) => {
      // if (error.response == undefined) return
      const errRes = error.response
      if (errRes.status === 401) {
        // store.commit("user/SET_TOKEN", null)
        Message({
          message: "身份验证失败，请重新登录",
          type: "error",
          duration: 5 * 1000
        })
        localCache.deleteCache(TOKEN)
        router.push("/login")
      } else if (errRes.status === 404) {
        Message({
          message: "请查看接口路径是否存在",
          type: "error",
          duration: 5 * 1000
        })
      } else {
        Message({
          message: error,
          type: "error",
          duration: 5 * 1000
        })
      }
      return Promise.reject(errRes)
    }
  )
  return service(apiConfig)
}
